package com.evolution.common.web.autoconfigure;

import com.evolution.common.core.utils.StringUtils;
import com.evolution.common.web.autoconfigure.properties.XssProperties;
import com.evolution.common.web.filter.RepeatableFilter;
import com.evolution.common.web.filter.XssFilter;
import jakarta.servlet.DispatcherType;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

import java.util.HashMap;
import java.util.Map;

/**
 * Class: FilterAutoConfiguration
 * <p>
 * desc: 过滤器自动配置
 * </p>
 * create date: 2024-03-13 11:43:03
 *
 * @author cao.yong
 */
@AutoConfiguration
@EnableConfigurationProperties(XssProperties.class)
public class FilterAutoConfiguration {

    @Bean
    @ConditionalOnProperty(prefix = XssProperties.PREFIX, name = "enabled", havingValue = "true")
    public FilterRegistrationBean<XssFilter> xssFilterRegistration(XssProperties xssProperties) {
        FilterRegistrationBean<XssFilter> registration = new FilterRegistrationBean<>();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new XssFilter());
        registration.addUrlPatterns(StringUtils.splitToArray(xssProperties.getUrlPatterns(), StringUtils.COMMA));
        registration.setName("xssFilter");
        registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
        Map<String, String> initParameters = new HashMap<>();
        initParameters.put("excludes", xssProperties.getExcludes());
        registration.setInitParameters(initParameters);
        return registration;
    }

    @Bean
    public FilterRegistrationBean<RepeatableFilter> someFilterRegistration() {
        FilterRegistrationBean<RepeatableFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new RepeatableFilter());
        registration.addUrlPatterns("/*");
        registration.setName("repeatableFilter");
        registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
        return registration;
    }
}
